﻿//-----------------------------------------------------------------------
// <copyright file="WebflowAccessableAttribute.cs" company="Sławomir Rosiek">
//     Copyright (c) Sławomir Rosiek. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Rosieks.Web.Flow
{
    using System.Web.Mvc;

    public class WebflowAccessableAttribute : ActionFilterAttribute
    {
        private IWebflowManager webflowManager;

        public IWebflowManager Manager
        {
            get
            {
                if (this.webflowManager == null)
                {
                    this.webflowManager = new WebflowManager();
                }

                return this.webflowManager;
            }

            set
            {
                this.webflowManager = value;
            }
        }

        /// <summary>
        /// Gets or sets the name of the workflow.
        /// </summary>
        /// <value>The name of the workflow.</value>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the parameter which value determine name of the workflow.
        /// </summary>
        /// <value>The parameter which value determine name of the workflow.</value>
        public string NameByParam
        {
            get;
            set;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            this.Manager.Load(filterContext.Controller.ControllerContext, this.GetWebflowName(filterContext));
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            this.Manager.Save(filterContext.Controller.ControllerContext);
        }

        protected virtual string GetWebflowName(ActionExecutingContext filterContext)
        {
            string webflowName = this.Name;

            if (!string.IsNullOrWhiteSpace(this.NameByParam))
            {
                var name = filterContext.HttpContext.Request[this.NameByParam];
                if (name != null)
                {
                    webflowName = name.ToString();
                }
            }

            return webflowName;
        }
    }
}
